import {
  defineComponent,
  PropType,
  reactive,
  watch,
  ref,
  onMounted
} from 'vue';
import { SubListState } from './type';
import { SetupContext } from '@vue/runtime-core';
import { getFormDesignManagement } from '@/https/api/form-management';

export default defineComponent({
  props: {
    /**
     * v-model
     */
    modelValue: {
      type: Object,
      default: () => ({
        formKey: '',
        userId: '',
        type: '1'
      }),
      required: true
    },
    /**
     * 原型对象（用于new）
     */
    model: {
      type: Object as PropType<{ [key: string]: string }>,
      default: () => Object.assign({})
    }
  },
  emits: ['update:modelValue'],
  setup(props: any, ctx) {
    const sublistState = reactive({
      data: props.modelValue.type,
      type: props.modelValue.type,
      userId: props.modelValue.userId,
      formKey: props.modelValue.formKey,
      returnableTaskNode: props.modelValue.returnableTaskNode,
      editing: false,
      editItem: {},
      editIndex: undefined,
      isNew: false,
      sublistForm: null
    });

    // SubList表单
    const form = ref();
    onMounted(() => {
      sublistState.sublistForm = form.value;
      getFormList();
    });

    const formList = ref([]);

    async function getFormList() {
      try {
        const { data: res } = await getFormDesignManagement('select');
        formList.value = res.data;
      } catch (e) {
        console.log(e);
      }
    }

    watch([() => sublistState.formKey], () => {
      ctx.emit('update:modelValue', {
        formKey: sublistState.formKey
      });
    });

    return {
      sublistState,
      form,
      formList
    };
  },
  render() {
    const props = this.$props;
    const sublistState = this.sublistState;
    const formList = this.formList;

    return (
      <div class="sublist-div">
        <el-form-item label="表单">
          <el-select v-model={sublistState.formKey} placeholder="请选择">
            {formList.map((item) => (
              <el-option
                key={item.formId}
                label={item.formName}
                value={item.formId}
              />
            ))}
          </el-select>
        </el-form-item>
      </div>
    );
  }
});
